import query from '@dfeidao/atom-nodejs/db/query';
import log from '@dfeidao/atom-nodejs/logger/log';
import send_msg from '@dfeidao/send-msg/nodejs';

// import get_user_by_usercode from '@dfeidao/atom-nodejs/msg/get-user-by-usercode';
import format from '@feidao/web/atom/core/dt/format';
import { IncomingHttpHeaders } from 'http';

import { systemid, productid } from '../atom/config';

interface Message {
	name: string;
}

interface IEquipment {
	_id: string;
	equip_no: string;
	equip_name: string;
	Date: string;
	state: string;
}

interface IWebResult {
	data: unknown;
	cookie?: {
		[name: string]: string;
	} | null;
	content_type?: string;
	headers?: {
		[key: string]: string;
	};
	attachment?: string;
	redirect?: string;
	status_code?: number;
}

export default async function atom(message: Message, action_id: string, session_id: string, headers: IncomingHttpHeaders): Promise<IWebResult> {
	log('Service begin path:app-equip_list/s002,action_id:' + action_id);

	const { exec, prepare } = query(action_id, session_id, systemid);
	prepare('equipment', ['_id', 'equip_no', 'equip_name'], {
		equip_name: { $regex: '^.*' + message.name + '.*$', $options: 'i' }
	}, 500, 1, [], []);
	// 根据usercode获取companyid
	const [equip] = await exec<IEquipment>();
	const e_nos = equip.map((item) => {
		return item.equip_no;
	});

	const state = await send_msg({ actionid: action_id, sessionid: session_id }, 'loginservice.getusersessionsbyusercode', {
		productid,
		usercode: e_nos
	});

	// const state = await get_user_by_usercode(action_id, session_id, "self_sell", "self_sell", e_nos);
	e_nos.forEach((item: string, i: number) => {
		if (state[item].length > 0) {
			const time = state[item][0].lastReplyTime;
			equip[i].Date = format(time, 2);
			equip[i].state = "在线";
		} else {
			equip[i].Date = "";
			equip[i].state = "离线";
		}
	});


	log('Service end path:app-equip_list/s002,action_id:' + action_id);
	return {
		data: equip
	};
}
